package main

import (
	"github.com/astaxie/beego/logs"
	"github.com/hpcloud/tail"
)

var tailObjMgr *TailObjMgr

type TailObj struct {
	tail *tail.Tail
	conf CollectConf
}

type TailObjMgr struct {
	tails   []*TailObj
	msgChan chan *TextMsg
}

type TextMsg struct {
	Msg   string
	Topic string
}

func GetMsg() (msg *TextMsg) {
	msg = <-tailObjMgr.msgChan
	return
}

func initTailf(conf []CollectConf) (err error) {

	tailObjMgr = &TailObjMgr{
		msgChan: make(chan *TextMsg, 100),
	}
	for _, value := range conf {
		obj := &TailObj{
			conf: value,
		}
		tails, err := tail.TailFile(value.logPath, tail.Config{
			ReOpen:    true,
			Follow:    true,
			MustExist: false,
			Poll:      true,
		})
		if err != nil {
			logs.Debug(err)
			return
		}
		obj.tail = tails

		tailObjMgr.tails = append(tailObjMgr.tails, obj)
		go readFromTail(obj)
	}
	return
}

func readFromTail(obj *TailObj) {
	for true {
		//读一行日志
		line, ok := <-obj.tail.Lines
		if !ok {
			logs.Warn("tail file reopen fileName", obj.tail.Filename)
			continue
		}
		texMsg := &TextMsg{
			Msg:   line.Text,
			Topic: obj.conf.topic,
		}
		tailObjMgr.msgChan <- texMsg

	}
}
